from rest_framework import serializers
from users.models import User
from django.contrib.auth.models import Group

#1, admin序列化器
class AdminSerializers(serializers.ModelSerializer):
    class Meta:
        model = User
        # fields = ["id","username","email","mobile","password","groups","user_permissions"]
        fields = "__all__"

        extra_kwargs = {
            "password":{
                "write_only":True
            }
        }

    #1,重写create方法,设置管理员属性,密码加密
    def create(self, validated_data):

        #1, 添加is_staff&is_superuser
        validated_data["is_staff"] = True
        validated_data["is_superuser"] = True

        #2, 创建用户对象
        user = super().create(validated_data)

        #加密密码, 内部使用的是sha256算法
        user.set_password(validated_data["password"])
        user.save()

        #3,返回结果
        return user

    #2,重写create方法,管理员密码加密
    def update(self, instance, validated_data):
        #1,修改基本信息
        user  = super().update(instance,validated_data)

        #2,密码加密
        user.set_password(validated_data["password"])
        user.save()

        #3,返回数据
        return user

#2, group simple
class GroupSimpleSerializers(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ["id","name"]